var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    text: "获取验证码",
    codeType: false,
    isCode:true,
    phone: '',
    code: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  bindPhone(event) {
    this.setData({
      phone: event.detail.value
    });
  },
  bindCode(event) {
    this.setData({
      code: event.detail.value
    });
  },
  goCode: function() {
   
    let num = 60;
    let that = this;
    let phone = that.data.phone;

    if (phone == '') {
      util.showErrorToast('请输入手机号码');
      return false;
    }
    that.setData({
      isCode: false
    });
    wx.showLoading({
      titleL:"发送验证码",
      mask:true
    });
    util.request(api.ToSendMsgUrl, {
      phone: phone
    }).then(function(res) {
      wx.hideLoading();
      if (res.success) {
        let timer = setInterval(() => {
          if (num <= 0) {
            clearInterval(timer);
            that.setData({
              codeType: false,
              text: "获取验证码",
              isCode: true
            });
            return;
          }
          that.setData({
            text: num + 's'
          });
          num--;
        }, 1000);
        that.setData({
          codeType: true
        });
        wx.showToast({
          title: res.message
        })

      } else {
        wx.showToast({
          title: res.message
        })
      }
    });
  },
  toNext: function() {
    let phone = this.data.phone;
    let code = this.data.code;

    if (phone == '') {
      util.showErrorToast('请输入手机号码');
      return false;
    }
    if (!util.checkPhone(phone)) {
      util.showErrorToast('请输入正确的手机号码');
      return false;
    }

    if (code == '') {
      util.showErrorToast('请输入短信验证码');
      return false;
    }

    util.requestPost(api.ToLoginUrl, {
      phone: phone,
      code: code
    }).then(function(res) {
      if (res.success) {
        if (!res.data) {
          wx.navigateTo({
            url: '/pages/register/register2/register2?phone=' +phone
          })
        } else {
          wx.setStorageSync('user', res.data);
          wx.setStorageSync('token', res.data.token);
          wx.navigateBack({})
        }


      } else {
        wx.showToast({
          title: res.message
        })
      }
    });
  }
})